<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>websocket测试程序 </title>
    <script>
        window.addEventListener("load", function (evt) {
            var output = document.getElementById("output");
           
            var ws;
            var print = function (message) {
                var d = document.createElement("div");
                d.innerHTML = message;
                output.appendChild(d);
            };

            document.getElementById("open").onclick = function (ev) {
                if (ws) {
                    return false;
                }
                ws = new WebSocket("ws://47.52.77.233:8777/ws");
                ws.onopen = function (ev) {
                    print("连接成功");
                };
                ws.onclose = function (ev) {
                    print("连接关闭");
                };
                ws.onerror = function (ev) {
                    print("发生错误 " + ev.data)
                };

                ws.onmessage = function (ev1) {
                    print("服务端消息: " + ev1.data)
                };

                return false
            };

            //发给自己
            document.getElementById("list").onclick = function(ev){
                if(!ws)
                {
                    return false;
                }
                console.log(ws)
                 ws.send('{"to":"","type":1,"msg":""}')
            }
             //发给所有人
            document.getElementById("broadcast").onclick = function(ev){
                if(!ws)
                {
                    return false;
                }
                console.log(ws)
                 ws.send('{"to":"","type":2,"msg":"给所有人"}')
            }
             //发给自己
            document.getElementById("touser").onclick = function(ev){
                if(!ws)
                {
                    return false;
                }
                var input = document.getElementById("user")
                 ws.send('{"to":"'+input.value+'","type":3,"msg":"发给'+input.value+' 的消息"}')
            }

            document.getElementById("close").onclick = function (ev) {
                if (ws) {
                    ws.close()
                }
            }

        })

    </script>
</head>

<body>

    <div>

        <br>
        <input type="button" value="连接" id="open">
        <input type="button" value="在线列表" id="list">
        <input type="button" value="发广播" id="broadcast">
        <input type="button" value="发送给" id="touser">
        <input type="text" id="user">
        <input type="button" value="关闭" id="close">

    </div>
    <div id="output">

    </div>

</body>

</html>